package cn.zkdcloud.novel;

import cn.zkdcloud.annotation.MessageProcess;
import cn.zkdcloud.component.message.AbstractResponseMessage;
import cn.zkdcloud.component.message.acceptMessage.Event;
import cn.zkdcloud.component.message.acceptMessage.eventMessage.SubscribeEventMessage;
import cn.zkdcloud.component.message.acceptMessage.normalMessage.AcceptTextMessage;
import cn.zkdcloud.component.message.responseMessage.ResponseTextMessage;
import cn.zkdcloud.core.MessageComponent;
import cn.zkdcloud.util.AssertUtil;
import cn.zkdcloud.util.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author zk
 * @version 2017/9/29
 */
@RestController
@MessageProcess
public class NovelProcess {

    public String welcome = "欢迎订阅《我看小说订阅号》!(虽然测试号没有名字)\n"
            + "功能1：回复：订阅-小说名 即可订阅\n"
            + "功能2：回复：添加-小说名-小说更新地址 即可添加您想订阅的小说\n";

    private NovelUtil novelUtil = new NovelUtil();

    /**
     * 微信校验介入
     *
     * @param signature signature
     * @param timestamp timestamp
     * @param nonce     nonce
     * @param echostr   echostr
     * @return ret
     */
    @GetMapping(value = "/wechatOn")
    public String involved(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) {
        return WeChatUtil.confirm(signature, timestamp, nonce, echostr);
    }

    /**
     * 被动消息处理
     *
     * @param request request
     * @return messageRet
     */
    @PostMapping(value = "/wechatOn")
    public String dispatch(HttpServletRequest request) {
        return MessageComponent.getInstance().doAdapter(request);
    }

    /**
     * 关注/取消关注事件
     *
     * @param message message
     * @return ret
     */
    public AbstractResponseMessage subscribe(SubscribeEventMessage message) {
        if (Event.SUBSCRIBE == message.getEvent()) {
            return new ResponseTextMessage(welcome);
        } else {
            for (Map.Entry<String, List<String>> entry : novelUtil.usersubscribes.entrySet()) {
                List<String> openIds = entry.getValue();
                openIds.remove(message.getFromUserName());
            }
            return null;
        }
    }

    /**
     * 文本操作入口
     *
     * @param message message
     * @return reply
     */
    public AbstractResponseMessage replyText(AcceptTextMessage message) {
        String cmd = message.getContent();
        if (cmd.startsWith("订阅")) {
            String novelName = cmd.substring(3);

            if(novelUtil.subscribeNovel(novelName,message.getFromUserName())){ //subscribe novel
                return new ResponseTextMessage("订阅成功");
            } else {
                return new ResponseTextMessage("订阅号还么有收藏该小说，可以通过添加选项来添加哦~");
            }

        } else if (cmd.startsWith("添加")){
            String newNovelName = cmd.substring(cmd.indexOf("-") + 1,cmd.indexOf("-",cmd.indexOf("-") + 1));
            String newNovelUrl = cmd.substring(cmd.indexOf("-",cmd.indexOf("-") + 1) + 1);

            if(AssertUtil.isNullOrEmpty(new String[]{newNovelName,newNovelUrl})){
                return new ResponseTextMessage("输入项不能为空~");
            }

            try {
                novelUtil.addNovel(newNovelName,newNovelUrl);// add novel
                NovelUtil.usersubscribes.put(newNovelName,new ArrayList<>());// add new subscribe novel
                novelUtil.subscribeNovel(newNovelName,message.getFromUserName());
            } catch (Exception e) {
                return new ResponseTextMessage("添加失败，请输入项检查后重试");
            }
            return new ResponseTextMessage("添加成功，该小说会继续给您同步推送~");
        } else {
            return new ResponseTextMessage(welcome);
        }
    }


}
